package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.HealthAdvice;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.JwtUtils2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * 处理会员相关操作
 */

@RestController
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    //手机号快速登录
    @RequestMapping("/login")//160207
    public Result login(HttpServletResponse response, @RequestBody Map map) {
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //从Redis中获取保存的验证码
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if (validateCodeInRedis != null && validateCode != null && validateCode.equals(validateCodeInRedis)) {
            //验证码输入正确
            //判断当前用户是否为会员（查询会员表来确定）
            Member member = memberService.findByTelephone(telephone);
            if (member == null) {
                //不是会员，自动完成注册（自动将当前用户信息保存到会员表）
                member = new Member();
                member.setRegTime(new Date());
                member.setPhoneNumber(telephone);
                memberService.add(member);
            }
            //向客户端浏览器写入Cookie，内容为手机号
            telephone= JwtUtils2.encodeTelephone(telephone);//todo-----------------
            Cookie cookie = new Cookie("login_member_telephone", telephone);
            cookie.setPath("/");
            cookie.setMaxAge(60 * 60 * 24 * 30);
            response.addCookie(cookie);
            //将会员信息保存到Redis
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone, 60 * 30 * 100, json);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        } else {
            //验证码输入错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

    //2.1 更新用户信息 POST /member/update.do
    @PostMapping("/update")
    public Result update(@RequestBody Member member) {
        Result result = memberService.update(member);
        String json = JSON.toJSON(member).toString();
        jedisPool.getResource().setex(member.getPhoneNumber(), 60 * 30 * 100, json);
        return result;
    }

    //2.2 更新用户的手机号或密码  POST  member/updateTelOrPwd.do?newPhoneNumber=15632621046&newPassword=123
    @PostMapping("/updateTelOrPwd")
    public Result updateTelOrPwd(@RequestBody Member member, String newPhoneNumber, String newPassword, String validateCode, HttpServletResponse response) {
        String validateCodeInRedis = jedisPool.getResource().get(newPhoneNumber + RedisMessageConstant.SENDTYPE_UPDATE_PASSWORD_TELEPHONE);
        if (!(validateCodeInRedis != null && validateCode != null && validateCode.equals(validateCodeInRedis)))
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        String oldPhoneNumber = member.getPhoneNumber();
        member.setPhoneNumber(newPhoneNumber);
        member.setPassword(newPassword);
        Result result = memberService.update(member);
        jedisPool.getResource().del(oldPhoneNumber);
        String json = JSON.toJSON(member).toString();
        //向客户端浏览器写入Cookie，内容为手机号
        newPhoneNumber=JwtUtils2.encodeTelephone(newPhoneNumber);//todo------------------------
        Cookie cookie = new Cookie("login_member_telephone", newPhoneNumber);
        cookie.setPath("/");
        cookie.setMaxAge(60 * 60 * 24 * 30);
        response.addCookie(cookie);
        jedisPool.getResource().setex(newPhoneNumber, 60 * 30 * 100, json);
        return result;
    }

    //3. 根据rookie中的手机号回显用户信息  POST /member/findMemberInfo.do
    @PostMapping("/findMemberInfo")
    public Result findMemberInfo(HttpServletRequest req) {
        try {
            //获取cookie中的手机号
            Cookie[] cookies = req.getCookies();
            if (cookies == null) return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
            String phoneNumber = null;
            for (Cookie cookie : cookies) {
                if ("login_member_telephone".equals(cookie.getName())) {
                    phoneNumber = cookie.getValue();
                    phoneNumber=JwtUtils2.decodeTelephone(phoneNumber);//todo-------------
                    break;
                }
            }
            if (phoneNumber == null) return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
            String result = jedisPool.getResource().get(phoneNumber + RedisMessageConstant.SENDTYPE_LOGIN);
            if (StringUtils.isEmpty(result)) return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
            String memberJson = jedisPool.getResource().get(phoneNumber);
            Member member = JSON.parseObject(memberJson, Member.class);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    //健康干预回显消息  GET   /member/findhealthAdvice.do
    @GetMapping("/findhealthAdvice")
    public Result findhealthAdvice(HttpServletRequest req) {
        try {
            //获取cookie中的手机号
            Cookie[] cookies = req.getCookies();
            if (cookies == null) return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
            String phoneNumber = null;
            for (Cookie cookie : cookies) {
                if ("login_member_telephone".equals(cookie.getName())) {
                    phoneNumber = cookie.getValue();
                    phoneNumber=JwtUtils2.decodeTelephone(phoneNumber);//todo-------------
                    break;
                }
            }
            if (phoneNumber == null) return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
            String result = jedisPool.getResource().get(phoneNumber + RedisMessageConstant.SENDTYPE_LOGIN);
            if (StringUtils.isEmpty(result)) return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
            String memberJson = jedisPool.getResource().get(phoneNumber);
            Member member = JSON.parseObject(memberJson, Member.class);
            HealthAdvice healthAdvice = memberService.findHealthAdvice(member.getId());
            if (healthAdvice == null) return new Result(false, MessageConstant.MEMBER_INFO_NOT_EXISTS);
            return new Result(true, MessageConstant.GET_HEALTH_ADVICE_SUCCESS, healthAdvice);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_HEALTH_ADVICE_FAIL);
        }
    }
}
